import subprocess
import psutil
import time
import os

exe_path = os.path.abspath("main.exe")
process_name = "main.exe"

# 结束已有进程
for proc in psutil.process_iter(['pid', 'name']):
    if proc.info['name'] == process_name:
        print(f"发现已有 {process_name}，PID: {proc.info['pid']}，终止中...")
        proc.terminate()
        try:
            proc.wait(timeout=5)
            print("已终止旧进程。")
        except psutil.TimeoutExpired:
            print("强制终止超时。")

# 启动新进程（后台运行）
print(f"正在启动 {exe_path} ...")
subprocess.Popen([exe_path], creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP)

# 等待并确认
time.sleep(3)
running = any(proc.info['name'] == process_name for proc in psutil.process_iter(['name']))
if running:
    print("启动成功：main.exe 正在运行。")
else:
    print("启动失败，请检查 main.exe 是否正常。")
